<template>
  <div class="relationship-consultation">
    <div class="container py-4">
      <h1 class="text-center mb-4">姻缘咨询</h1>
      
      <div class="points-info mb-3">
        <div class="row g-2 justify-content-center">
          <div class="col-auto">
            <div class="points-badge total-points">
              <i class="bi bi-coin me-2"></i>积分余额: {{ userPoints }}
            </div>
          </div>
          <div class="col-auto" v-if="lastConsumedPoints > 0">
            <div class="points-badge consumed-points">
              <i class="bi bi-dash-circle me-2"></i>本次消耗: {{ lastConsumedPoints }}
            </div>
          </div>
        </div>
      </div>
      
      <div class="row">
        <div class="col-lg-8 mx-auto">
          <div class="card shadow">
            <div class="card-body">
              <div class="chat-container">
                <div class="chat-messages" ref="chatMessages">
                  <template v-for="(message, index) in messages" :key="index">
                    <div v-if="message.type === 'user'" class="message user-message">
                      <div class="message-content">
                        {{ message.text }}
                      </div>
                      <div class="message-footer">
                        <div class="message-time">{{ formatTime(message.timestamp) }}</div>
                        <div class="message-actions">
                          <copy-button :content="message.text" title="复制问题"></copy-button>
                        </div>
                      </div>
                    </div>
                    
                    <div v-else class="message system-message" :class="{ 
                      'typing-message': message.isTyping,
                      'special-message': message.isSpecial,
                      'info-message': message.isInfo
                    }">
                      <div v-if="message.isTyping && !message.text" class="loading-dots">
                        <span></span>
                        <span></span>
                        <span></span>
                      </div>
                      <div v-else class="message-content">
                        <span v-html="message.text"></span>
                        <span v-if="message.isTyping" class="typing-cursor"></span>
                        <button v-if="message.hasRechargeButton" 
                          @click="goToRecharge" 
                          class="btn btn-recharge btn-lg mt-3">
                          <i class="bi bi-credit-card me-2"></i>
                          立即充值获取积分
                        </button>
                      </div>
                      <div class="message-footer">
                        <!-- 复制按钮和时间戳在同一行显示 -->
                        <div class="message-time">{{ formatTime(message.timestamp) }}</div>
                        <div class="message-actions" v-if="!message.isTyping">
                          <copy-button :content="message.text" title="复制回答"></copy-button>
                        </div>
                      </div>
                    </div>
                  </template>
                  
                  <div v-if="isWaitingForResponse" class="message system-message loading-message">
                    <div class="message-content">
                      <div class="thinking-animation">
                        <span>天机推衍</span>
                        <span class="thinking-dots">
                          <span>.</span>
                          <span>.</span>
                          <span>.</span>
                        </span>
                      </div>
                    </div>
                  </div>
                </div>
                
                <div class="chat-input-wrapper">
                  <div class="input-group custom-input-group">
                    <div class="input-icon">
                      <i class="bi bi-heart"></i>
                    </div>
                    <input 
                      type="text" 
                      class="form-control custom-input" 
                      placeholder="请输入您的姻缘问题..." 
                      v-model="userInput"
                      @keyup.enter="validateAndSend"
                      :class="{'is-invalid': showInputError}"
                      :disabled="isLoading"
                    >
                    <button 
                      class="btn btn-send" 
                      @click="validateAndSend"
                      :disabled="isLoading"
                    >
                      <i class="bi" :class="[isLoading ? 'bi-hourglass-split' : 'bi-send-fill']"></i>
                      <span>{{ isLoading ? '天机推衍...' : '姻缘分析' }}</span>
                    </button>
                  </div>
                  <div class="invalid-feedback" v-if="showInputError">
                    请输入您想咨询的问题
                  </div>
                </div>
              </div>
            </div>
          </div>
          
          <div class="card mt-4 question-card">
            <div class="card-header bg-light">
              <h5 class="mb-0">
                <i class="bi bi-heart me-2"></i>
                姻缘咨询常见问题
              </h5>
            </div>
            <div class="card-body">
              <div class="quick-questions">
                <button 
                  v-for="(question, index) in suggestedQuestions" 
                  :key="index"
                  class="btn btn-question me-2 mb-2"
                  @click="askSuggestedQuestion(question)"
                  :disabled="isLoading"
                >
                  <i class="bi bi-chat-text me-2"></i>
                  {{ question }}
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { useUserStore } from '../store/userStore'
import { mapState } from 'pinia'
import { askService } from '../api'
import CopyButton from '../components/CopyButton.vue'

export default {
  name: 'Relationship',
  components: {
    CopyButton
  },
  data() {
    return {
      userInput: '',
      showInputError: false,
      isLoading: false,
      isWaitingForResponse: false, // 是否正在等待API首次响应
      // 积分系统相关
      pointsPerQuestion: 10, // 每次提问消耗的积分
      lastConsumedPoints: 0, // 上次消耗的积分
      typingSpeed: 10, // 打字机效果的速度（毫秒/字符）
      messages: [
        {
          type: 'system',
          text: '您好，欢迎来到姻缘咨询。我可以帮您分析感情线索、桃花运势及配对合适度，请问有什么想了解的？',
          timestamp: new Date()
        }
      ],
      suggestedQuestions: [
        '今年我的桃花运如何？',
        '我什么时候会遇到合适的伴侣？',
        '我与当前伴侣的合适度如何？',
        '我适合什么类型的伴侣？'
      ],
      // 预设回答库（备用）
      responseMap: {
        '今年我的桃花运如何？': '根据您的八字，今年桃花运不错，尤其在春季和秋季。您的贵人星较为活跃，有机会通过社交场合或朋友介绍认识新的异性朋友。',
        '我什么时候会遇到合适的伴侣？': '分析您的命盘，未来1-2年内有较大机会遇到合适的伴侣，尤其在您28-30岁这个年龄段，姻缘宫位较为旺盛。',
        '我与当前伴侣的合适度如何？': '若要准确分析需要对方的出生信息，但从您的命盘来看，您适合与性格温和、事业心较强的伴侣相处，若对方符合这些特点，合适度较高。',
        '我适合什么类型的伴侣？': '您的命盘显示，您适合与比您年长2-3岁，性格稳重且有一定事业基础的伴侣。五行上，水或金属性较强的人会与您形成良好互补。'
      }
    }
  },
  computed: {
    ...mapState(useUserStore, ['userPoints'])
  },
  methods: {
    validateAndSend() {
      // 检查用户输入是否为空
      if (!this.userInput.trim()) {
        this.showInputError = true;
        setTimeout(() => {
          this.showInputError = false;
        }, 3000);
        return;
      }
      
      this.showInputError = false;
      
      // 检查积分是否足够
      if (this.userPoints < this.pointsPerQuestion) {
        // 积分不足，显示提示信息
        this.messages.push({
          type: 'system',
          text: `<div class="points-warning"><i class="bi bi-exclamation-triangle me-2"></i>您的积分不足，无法继续咨询。每次咨询需要消耗 ${this.pointsPerQuestion} 积分，您当前剩余 ${this.userPoints} 积分。</div>`,
          isSpecial: true,
          hasRechargeButton: true,
          timestamp: new Date()
        });
        return;
      }
      
      // 记录用户输入
      const userMessage = {
        type: 'user',
        text: this.userInput,
        timestamp: new Date()
      };
      
      this.messages.push(userMessage);
      
      // 清空输入框
      const userInput = this.userInput;
      this.userInput = '';
      
      // 设置加载状态
      this.isLoading = true;
      this.isWaitingForResponse = true;
      
      // 滚动到底部
      this.$nextTick(() => {
        this.scrollToBottom();
      });
      
      // 尝试从预设回答中获取，如果有预设回答则使用（真实环境下替换为API调用）
      let presetResponse = this.responseMap[userInput.trim()];
      
      // 调用后端API
      const apiCall = () => {
        askService({
          question: userInput,
          type: 'relationship', // 姻缘咨询类型
          pointsCost: this.pointsPerQuestion // 提供积分消耗信息
        })
        .then(response => {
          // 关闭等待响应状态
          this.isWaitingForResponse = false;
          
          if (response.error) {
            // 处理错误情况
            this.handleApiError(response.error);
            return;
          }
          
          if (response.needPoints && response.pointsShortage) {
            // 积分不足的情况
            this.handlePointsShortage(response.pointsShortage);
            return;
          }
          
          // 记录积分消耗
          if (response.pointsConsumed) {
            this.lastConsumedPoints = response.pointsConsumed;
            // 更新 Pinia 存储中的用户积分
            const userStore = useUserStore();
            userStore.updatePoints(-response.pointsConsumed);
          }
          
          // 创建打字机效果的系统响应消息
          const systemMessage = {
            type: 'system',
            text: '',
            fullText: response.answer || '很抱歉，我暂时无法回答这个问题。请尝试其他问题或稍后再试。',
            isTyping: true,
            timestamp: new Date()
          };
          
          this.messages.push(systemMessage);
          
          // 开始打字机效果
          this.typewriterEffect(systemMessage);
        })
        .catch(error => {
          // 关闭等待响应状态
          this.isWaitingForResponse = false;
          console.error('API调用出错:', error);
          
          // 显示错误消息
          this.messages.push({
            type: 'system',
            text: '很抱歉，服务器暂时无法响应，请稍后再试。',
            isInfo: true,
            timestamp: new Date()
          });
          
          this.isLoading = false;
          this.$nextTick(() => {
            this.scrollToBottom();
          });
        });
      };
      
      // 使用预设回答（开发环境使用，生产环境移除）
      if (presetResponse) {
        // 关闭等待响应状态
        setTimeout(() => {
          this.isWaitingForResponse = false;
          
          // 记录积分消耗（模拟）
          this.lastConsumedPoints = this.pointsPerQuestion;
          
          // 更新 Pinia 存储中的用户积分（模拟）
          const userStore = useUserStore();
          userStore.updatePoints(-this.pointsPerQuestion);
          
          // 创建打字机效果的系统响应消息
          const systemMessage = {
            type: 'system',
            text: '',
            fullText: presetResponse,
            isTyping: true,
            timestamp: new Date()
          };
          
          this.messages.push(systemMessage);
          
          // 开始打字机效果
          this.typewriterEffect(systemMessage);
        }, 1500);
      } else {
        // 调用后端API
        apiCall();
      }
    },
    
    // 打字机效果
    typewriterEffect(message) {
      let i = 0;
      const fullText = message.fullText;
      const speed = this.typingSpeed;
      
      // 清除之前的计时器
      if (this.typewriterTimer) {
        clearInterval(this.typewriterTimer);
      }
      
      // 创建打字机计时器
      this.typewriterTimer = setInterval(() => {
        if (i < fullText.length) {
          message.text += fullText.charAt(i);
          i++;
          this.$nextTick(() => {
            this.scrollToBottom();
          });
        } else {
          // 打字效果完成
          clearInterval(this.typewriterTimer);
          message.isTyping = false;
          this.isLoading = false;
        }
      }, speed);
    },
    
    // 处理API错误
    handleApiError(error) {
      this.messages.push({
        type: 'system',
        text: `出现错误: ${error}`,
        isInfo: true,
        timestamp: new Date()
      });
      this.isLoading = false;
    },
    
    // 处理积分不足
    handlePointsShortage(shortage) {
      this.messages.push({
        type: 'system',
        text: `<div class="points-warning"><i class="bi bi-exclamation-triangle me-2"></i>您的积分不足，还需要 ${shortage} 积分才能继续咨询。</div>`,
        isSpecial: true,
        hasRechargeButton: true,
        timestamp: new Date()
      });
      this.isLoading = false;
    },
    
    // 转到充值页面
    goToRecharge() {
      this.$router.push('/recharge');
    },
    
    // 格式化时间
    formatTime(timestamp) {
      const date = new Date(timestamp);
      const hours = date.getHours().toString().padStart(2, '0');
      const minutes = date.getMinutes().toString().padStart(2, '0');
      return `${hours}:${minutes}`;
    },
    
    // 滚动到底部
    scrollToBottom() {
      const chatContainer = this.$refs.chatMessages;
      if (chatContainer) {
        chatContainer.scrollTop = chatContainer.scrollHeight;
      }
    },
    
    // 使用常见问题
    askSuggestedQuestion(question) {
      if (this.isLoading) return;
      
      this.userInput = question;
      this.validateAndSend();
    }
  }
}
</script>

<style scoped>
/* 姻缘咨询页面整体样式 */
.relationship-consultation {
  /* background-color: #faf5ff; */
  min-height: 100vh;
}

/* 积分显示 */
.points-info {
  display: flex;
  justify-content: center;
}

.points-badge {
  padding: 5px 12px;
  border-radius: 20px;
  font-weight: 500;
  display: flex;
  align-items: center;
}

.total-points {
  background-color: #e9f5ff;
  color: #0d6efd;
}

.consumed-points {
  background-color: #fff2e9;
  color: #fd7e14;
}

/* 聊天界面样式 */
.chat-container {
  display: flex;
  flex-direction: column;
  height: 65vh;
  position: relative;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 1rem;
  display: flex;
  flex-direction: column;
  gap: 1rem;
  margin-bottom: 60px;
}

.message {
  padding: 12px 15px;
  border-radius: 15px;
  max-width: 85%;
  position: relative;
  animation: fadeIn 0.3s ease-out;
}

.user-message {
  align-self: flex-end;
  background: linear-gradient(135deg, #4a6cf7 0%, #2954e0 100%);
  color: white;
  border-bottom-right-radius: 4px;
}

.system-message {
  align-self: flex-start;
  background: linear-gradient(135deg, #f5f7fa 0%, #e8edf2 100%);
  color: #333;
  border-bottom-left-radius: 4px;
  transition: all 0.3s ease;
  word-break: break-word;
  white-space: pre-wrap;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
}

.message-content {
  line-height: 1.5;
  word-break: break-word;
}

/* 消息底部信息栏 */
.message-footer {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 4px;
  gap: 8px;
  font-size: 0.75rem;
  color: rgba(255, 255, 255, 0.7);
}

.system-message .message-footer {
  color: #888;
}

.user-message .message-footer {
  color: rgba(255, 255, 255, 0.7);
}

.message-time {
  font-size: 0.75rem;
}

.message-actions {
  display: flex;
  align-items: center;
}

/* 输入框区域 */
.chat-input-wrapper {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 10px 15px;
  background-color: white;
  border-top: 1px solid #eee;
  border-bottom-left-radius: 8px;
  border-bottom-right-radius: 8px;
}

.custom-input-group {
  position: relative;
  border-radius: 25px;
  overflow: hidden;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.input-icon {
  position: absolute;
  left: 15px;
  top: 50%;
  transform: translateY(-50%);
  color: #7c3aed;
  z-index: 10;
}

.custom-input {
  border: none;
  padding-left: 45px;
  height: 50px;
  background-color: #f8f9fa;
}

.custom-input:focus {
  box-shadow: none;
  background-color: white;
}

.btn-send {
  background: linear-gradient(135deg, #9f7aea 0%, #7c3aed 100%);
  color: white;
  border: none;
  padding: 0.5rem 1.5rem;
  display: flex;
  align-items: center;
  gap: 8px;
}

.btn-send:hover {
  background: linear-gradient(135deg, #8b5cf6 0%, #6d28d9 100%);
  color: white;
}

.btn-send i {
  font-size: 1.1rem;
}

/* 问题卡片样式 */
.question-card {
  border-radius: 12px;
  border: none;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.05);
}

.btn-question {
  background-color: #f3ebff;
  color: #7c3aed;
  border: none;
  border-radius: 20px;
  transition: all 0.3s ease;
}

.btn-question:hover {
  background-color: #e9d8fd;
  transform: translateY(-2px);
}

.btn-recharge {
  background: linear-gradient(135deg, #f6ad55 0%, #ed8936 100%);
  border: none;
  color: white;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.btn-recharge:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(237, 137, 54, 0.4);
}

/* 加载动画 */
.loading-message {
  background-color: transparent !important;
  box-shadow: none !important;
}

.thinking-animation {
  display: flex;
  align-items: center;
  color: #6c757d;
  font-style: italic;
}

.thinking-dots span {
  animation: loadingDots 1.4s infinite ease-in-out both;
  margin-left: 2px;
}

.thinking-dots span:nth-child(1) {
  animation-delay: -0.32s;
}

.thinking-dots span:nth-child(2) {
  animation-delay: -0.16s;
}

.typing-cursor {
  display: inline-block;
  width: 2px;
  height: 16px;
  background-color: #333;
  margin-left: 2px;
  vertical-align: middle;
  animation: blink 0.7s infinite;
}

@keyframes blink {
  0%, 100% { opacity: 1; }
  50% { opacity: 0; }
}

.typing-message .message-content {
  position: relative;
}

/* 消息操作菜单样式 */
.message-actions {
  display: none;
  position: absolute;
  top: 8px;
  right: 8px;
  z-index: 2;
}

.message:hover .message-actions {
  display: block;
}

.message-content {
  position: relative;
  width: 100%;
}

.user-message .message-actions {
  color: white;
}

.system-message .message-actions {
  color: #333;
}

/* 特殊消息样式 */
.special-message {
  background: linear-gradient(135deg, #fff8e1 0%, #ffecb3 100%);
  border-left: 4px solid #ffc107;
}

.info-message {
  background: linear-gradient(135deg, #e3f2fd 0%, #bbdefb 100%);
  border-left: 4px solid #2196f3;
}

/* 加载中的动画点 */
.loading-dots {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 10px;
}

.loading-dots span {
  display: inline-block;
  width: 8px;
  height: 8px;
  margin: 0 3px;
  border-radius: 50%;
  background-color: #6c757d;
  opacity: 0.6;
  animation: loadingDots 1.4s infinite ease-in-out both;
}

.loading-dots span:nth-child(1) {
  animation-delay: -0.32s;
}

.loading-dots span:nth-child(2) {
  animation-delay: -0.16s;
}

@keyframes loadingDots {
  0%, 80%, 100% { transform: scale(0); }
  40% { transform: scale(1); }
}

/* 积分警告样式 */
.points-warning {
  background-color: #fff3cd;
  border-left: 4px solid #ffc107;
  padding: 12px;
  border-radius: 4px;
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

/* 淡入动画 */
@keyframes fadeIn {
  from { opacity: 0; transform: translateY(10px); }
  to { opacity: 1; transform: translateY(0); }
}
</style>